package com.hankol.winecellar.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.util.AttributeSet
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import java.math.BigDecimal

/**
 * 进度跟随进度条移动
 * https://blog.csdn.net/weixin_37188254/article/details/82767847
 */
class TextFollowingProgressBar : ProgressBar {
    private var mTextPaint: Paint? = null
    private var text: String? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initPaint()
    }

    private fun initPaint() {
        //初始化，画笔
        mTextPaint = Paint()
        mTextPaint!!.color = Color.WHITE
        mTextPaint!!.textSize = 34f
        mTextPaint!!.isAntiAlias = true
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    @Synchronized override fun setProgress(progress: Int) {
        setText(progress)
        super.setProgress(progress)
    }

    @Synchronized override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rect = Rect()
        mTextPaint!!.getTextBounds(text, 0, text!!.length, rect)
        //        获取一份宽度
        val percentileWidth = width.toDouble() / 100
        //        获取文字高度
        val y = height / 2 - rect.centerY()
        if (progress >= 0 && progress <= 5) {
            canvas.drawText(text!!, 0f, y.toFloat(), mTextPaint!!)
        } else {
            val pro = BigDecimal(percentileWidth * progress).setScale(0, BigDecimal.ROUND_HALF_UP).toString()
            if (progress > 5 && progress < 10) {
                val x = Integer.valueOf(pro) - rect.centerX() * 2
                canvas.drawText(text!!, x.toFloat(), y.toFloat(), mTextPaint!!)
            } else {
                val x = Integer.valueOf(pro) - rect.centerX() * text!!.length
                canvas.drawText(text!!, x.toFloat(), y.toFloat(), mTextPaint!!)
            }
        }
    }

    //设置文字内容
    private fun setText(progress: Int) {
        text = "$progress%"
    }

    companion object {
        private const val TAG = "TextFollowingProgressBar"
    }
}